import axios from 'axios'
import { ElMessage } from 'element-plus'

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE || '/api',
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers = config.headers || {}
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

instance.interceptors.response.use(
  (response) => {
    const contentType = response.headers?.['content-type'] || ''
    if (contentType.includes('application/octet-stream')) {
      return response
    }

    const data = response.data
    if (data && typeof data === 'object' && 'code' in data && 'data' in data) {
      if (data.code === 0 || data.code === 200) return data.data
      ElMessage.error(data.message || '请求失败')
      return Promise.reject(data)
    }
    return data
  },
  (error) => {
    const status = error.response?.status
    const msg = error.response?.data?.message || error.message || '网络错误'
    if (status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      // 可在此触发登出/跳转逻辑
    } else {
      ElMessage.error(msg)
    }
    return Promise.reject(error)
  }
)

export const get = (url, params, config = {}) => instance.get(url, { params, ...config })
export const post = (url, data, config = {}) => instance.post(url, data, config)
export const put = (url, data, config = {}) => instance.put(url, data, config)
export const del = (url, params, config = {}) => instance.delete(url, { params, ...config })
export const patch = (url, data, config = {}) => instance.patch(url, data, config)
export const upload = (url, formData, config = {}) =>
  instance.post(url, formData, { headers: { 'Content-Type': 'multipart/form-data' }, ...config })

export default instance 